<!--
 * @Description:轮播配置页面
 * @Author: Morgan
 * @Date: 2021-06-24 17:07:01
 * @LastEditors: Morgan
 * @LastEditTime: 2021-07-02 17:17:42
-->
<template>
  <!-- 轮播配置页面 -->
  <div class="customer_modal">
    <div class="btns">
      <el-button class="btn" type="primary" @click="toAdd">新增</el-button>
      <el-button
        class="btn"
        type="primary"
        @click="toPreview"
      >预览</el-button>
    </div>
    <!-- {{ carouselData }} -->
    <!-- 表格开始 -->
    <div>
      <el-table
        v-loading="loading"
        :data="carouselData"
        style="width: 100%"
        stripe
      >
        <el-table-column label="序号" type="index" />
        <el-table-column label="轮播图名称" prop="name" />
        <el-table-column label="轮播图描述" prop="introduce" />
        <el-table-column label="轮播图图片">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '正常'" type="success">{{
              scope.row.status
            }}</el-tag>
            <el-tag v-else type="danger">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="green_info"
              @click="toEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              class="red_info"
              @click="toDelete(scope.row.id)"
            >删除</el-button>
            <!-- <el-button
              type="text"
              class="blue_info"
            >停用</el-button> -->
            <el-button
              v-if="scope.row.status === '停用'"
              type="text"
              class="warning_info"
              @click="toChangeState(scope.row)"
            >启用</el-button>
            <el-button
              v-if="scope.row.status === '正常'"
              type="text"
              class="warning_info"
              @click="toChangeState(scope.row)"
            >停用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->
    <!-- 模态框开始 -->
    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @click="toClose">
      <!-- {{ form }} -->
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="轮播图片" :label-width="formLabelWidth" prop="url">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="form.introduce" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框结束 -->
    <!-- 轮播图显示 -->
    <el-dialog
      title="大屏预览"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      class="el-dialog_header"
    >
      <div el-dialog_body>
        <el-carousel autoplay>
          <el-carousel-item v-for="item in carouselData" v-if="item.status === '正常'" :key="item.id">
            <img :src="item.url" :alt="item.name" style="width:100%;height:100%">
          </el-carousel-item>
        </el-carousel>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { query, saveOrUpdate, deleteById } from '@/api/carousel'
import { showFileURL, uploadFileURL } from '@/utils/config'

export default {
  data() {
    return {
      carouselData: [],
      loading: false,
      formLabelWidth: '80px',
      visible: false,
      title: '',
      form: {},
      rules: {
        name: [
          {
            required: true,
            message: '请输入轮播图名称',
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }
        ]
      },
      showFileURL,
      uploadFileURL,
      imageUrl: '',
      dialogVisible: false
    }
  },
  computed: {},
  created() {
    this.queryCarouselData()
  },
  mounted() {},
  methods: {
    async queryCarouselData() {
      this.loading = true
      const res = await query()
      this.carouselData = res.data
      this.loading = false
    },
    toAdd() {
      this.queryCarouselData()
      // 清空表单数据
      this.form = {}
      this.imageUrl = ''
      this.title = '添加轮播图'
      this.visible = true
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.log(res,"==图片上传成功的res");
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(this.imageUrl);
      this.form.url = this.showFileURL + res.data.id
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    toSave() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          console.log('校验通过')
          const res = await saveOrUpdate(this.form)
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: '成功',
            message: res.success
          })
          this.queryCarouselData()
          // this.toClose();
          this.visible = false
        } else {
          return false
        }
      })
    },
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields()
    },
    toEdit(row) {
      this.queryCarouselData()
      // 设置表单数据
      this.form = { ...row }
      this.imageUrl = this.form.url
      this.title = '编辑产品消息'
      this.visible = true
    },
    // 删除轮播图
    toDelete(id) {
      this.$confirm('此操作将永久删除该轮播图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteById({ id })
          this.$notify.success({
            title: '成功',
            message: res.success
          })
          this.queryCarouselData()
        })
        .catch(() => {
          this.$notify.info({
            title: '取消',
            message: '已取消删除'
          })
        })
    },
    async toChangeState(data) {
      if (data.status == '正常') {
        data.status = '停用'
      } else {
        data.status = '正常'
      }
      const temp = {
        status: data.status,
        id: data.id
      }
      // 遍历对象
      // for (const key in temp) {
      //   // key是一个变量，代表的属性名
      //   // console.log(key, temp[key]);
      //   if (!temp[key]) {
      //     delete temp[key]
      //   }
      // }
      // console.log(temp)
      const res = await saveOrUpdate(temp)
      this.queryCarouselData()
    },
    // 预览
    toPreview() {
      this.dialogVisible = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }

  }
}
</script>
<style scoped>
.btns {
  display: flex;
}
</style>
